<?php
/**
 * Created by PhpStorm.
 * User: panchaozhi
 * Date: 2016/11/17
 * Time: 17:05
 */
namespace common\models\base;

use yii\db\ActiveRecord;

class BaseModel extends ActiveRecord
{
    /**
     * 获取文章的分页数据
     * @param $query
     * @param int $curPage
     * @param int $pageSize
     * @param null $search
     * @return array
     */
    public function getPages($query, $curPage = 1, $pageSize = 10, $search = null)
    {
        if ($search)
            $query = $query->andFilterWhere($search);
        
        $data['count'] = $query->count();
        if (! $data['count']) {
            return [
                'count' => 0,
                'curPage' => $curPage,
                'pageSize' => $pageSize,
                'start' => 0,
                'end' => 0,
                'data' => []
            ];
        }
        
        $curPage = (ceil($data['count'] / $pageSize) < $curPage ? ceil($data['count'] / $pageSize) : $curPage);
        
        // 当前页
        $data['curPage'] = $curPage;
        // 每页显示条数
        $data['pageSize'] = $pageSize;
        // 起始页和结束页
        $data['start'] = ($curPage - 1) * $pageSize + 1;
        $data['end'] = (ceil($data['count'] / $pageSize) == $curPage) ? $data['count'] : ($curPage - 1) * $pageSize + $pageSize;
        // 查询返回的数据
        $data['data'] = $query->offset(($curPage - 1) * $pageSize)
            ->limit($pageSize)
            ->asArray()
            ->All();
        
        return $data;
    }
}